<?php

namespace App\Providers;

use App\Models\Article;
use App\Models\Category;
use App\Models\Configuration;
use App\Models\LifeRecord;
use App\Models\Link;
use App\Models\Tag;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //分配前台通用的数据
        view()->composer('home/common/layout', function ($view) {
            $categorys = Category::select('id', 'name')->orderBy('sort', 'desc')->where('parent_id', 0)->get();
            $tags = Tag::has('articles')->withCount('articles')->get();

            $configuration = Configuration::pluck('val', 'key');

            $topArticles = Article::select('id', 'title')
                ->orderBy('recommend', 'desc')
                ->orderBy('created_at', 'desc')
                ->limit(10)
                ->get();

            $links = Link::select('title', 'link')
                ->orderBy('created_at')
                ->get();

            $life_records = LifeRecord::orderBy('created_at', 'desc')->get();

            // 分配数据
            $assign = compact('categorys', 'tags', 'topArticles', 'links', 'life_records', 'configuration');
            $view->with($assign);
        });
    }
}
